// pages/ucenter/editProduct/editProduct.js
import Toast from '../../../lib/vant-weapp/toast/toast';
var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');
var api = require('../../../config/api.js');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    content: '',  
    contentLength: 0,
    allBrandList: [],
    brandIndex:0,
    allCategoryList: [],
    categoryIndex:0,
    currentCategoryList: [],
    productName:"",
    currentPrice:0,
    productCount:1,
    productUnit:"件",
    attrName:"",
    attrTitle:'',
    productFiles:[],
    fileServiceLocation:'',
    fileList: [],
    productId:0 
  },
  bindBrandPickerChange: function(e) {
    let _allCategoryList = this.data.allCategoryList;
    // 当前品牌索引 
    let _brandIndex = e.detail.value;
    // 得到品牌id
    let _brandId = this.data.allBrandList[_brandIndex].id;

    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,
      categoryName:"车型" 
    }  
    _currentCategoryList.push(categoryObj);
    for (let idex = 0; idex < _allCategoryList.length; idex++) {
      const element = _allCategoryList[idex];
      if(element.brandId==_brandId){
        _currentCategoryList.push(element);
      }
    }

    this.setData({
      brandIndex: _brandIndex,
      currentCategoryList:_currentCategoryList,
      categoryIndex: 0
    });
  },
  bindCategoryPickerChange: function(e) {
    this.setData({
      categoryIndex: e.detail.value
    });
  },
  contentInput: function(e) {
    this.setData({
      contentLength: e.detail.cursor,
      content: e.detail.value,
    });
  },
  inputProductName: function(e) {
    this.setData({
      productName: e.detail.value,
    });
  },  
  inputCurrentPrice: function(e) {
    this.setData({
      currentPrice: e.detail.value,
    });
  },
  inputProductCount: function(e) {
    this.setData({
      productCount: e.detail.value,
    });
  },
  inputProductUnit: function(e) {
    this.setData({
      productUnit: e.detail.value,
    });
  },
  inputAttrName: function(e) {
    this.setData({
      attrName: e.detail.value,
    });
  },
  // 文件删除
  fileDelete(event) {
    const { index, name } = event.detail;
    var _fileList = this.data.fileList;
    for (let index2 = 0; index2 < _fileList.length; index2++) {
      if(index==index2){    
        _fileList.splice(index2, 1);
        break;
      }
    } 

    var _productFiles = this.data.productFiles;
    for (let index2 = 0; index2 < _productFiles.length; index2++) {
      if(index==index2){    
        _productFiles.splice(index2, 1);
        break;
      }
    } 

    this.setData({ 
      fileList:_fileList,
      productFiles:_productFiles,
    }); 
  },  
  //文件读取完成后的回调函数
  afterRead(event) {
    const { file, name } = event.detail;
    var that = this;    
    that.fileUpload(file);
  },
  fileUpload: function(req) {
      var that = this;  
      const uploadTask = wx.uploadFile({
      url: api.UploadBuyFiles,
      filePath: req[0].path,
      name: 'file',
      header: { 
        //'Content-Type': 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
        //'X-Litemall-Token': wx.getStorageSync('token')
        'X-fjb-Token': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res);
        var _res = JSON.parse(res.data); 
        if (_res.code === 200) { 
          
          var _fileList = that.data.fileList;
          var fileObj = {
            url: _res.dataObject.fileUrl,
            name: _fileList.length+1,
          }   
          
          var _productFiles = that.data.productFiles;
          console.log(_productFiles);
          
          var _newFileName = _res.dataObject.newFileName;
          _productFiles.push(_newFileName); 
          console.log(_productFiles);
          _fileList.push(fileObj);
          that.setData({  
            fileList:_fileList,
            productFiles:_productFiles,
          });

        }else{  
          wx.showToast({   
            title: _res.msg,
            icon: 'none',
            duration: 2000
          })
        } 
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })
    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress) 
      //console.log('已经上传的数据长度', res.totalBytesSent)
      //console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  submitRecycleInfo: function(e) {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let that = this;
    let _brandIndex = that.data.brandIndex;
    if (_brandIndex == 0) {
      util.showErrorToast('请选择品牌');
      return false;
    }

    let _categoryIndex = that.data.categoryIndex;
    if (_categoryIndex == 0) {
      util.showErrorToast('请选择车型');
      return false;
    }

    if (that.data.content == '') {
      util.showErrorToast('请输入反馈内容');
      return false;
    }
    
    var _productName = that.data.productName;
    if (_productName == '') {
      util.showErrorToast('请输入产品名称');
      return false;
    }

    var _currentPrice = that.data.currentPrice;
    if (_currentPrice == '') {
      util.showErrorToast('请输入价格');
      return false;
    }

    var _productCount = that.data.productCount;
    if (_productCount == '') {
      util.showErrorToast('请输入数量');
      return false;
    }

    var _productUnit = that.data.productUnit;
    if (_productUnit == '') {
      util.showErrorToast('请输入数量单位');
      return false;
    }

    var _attrName = that.data.attrName;
    if (_attrName == '') {
      util.showErrorToast('请输入属性名称');
      return false;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true,
      success: function() {
      }
    });
    
    util.request(api.RecycleUpdaterInfo, {
      productId:that.data.productId,
      brandId:that.data.allBrandList[_brandIndex].id,
      categoryId:that.data.currentCategoryList[_categoryIndex].id,
      productName:_productName,
      productDetails: that.data.content,
      currentPrice:_currentPrice,
      productCount:_productCount,
      productUnit:_productUnit,
      attrName:_attrName, 
      productFiles: that.data.productFiles
    }, 'POST').then(function(res) {
      wx.hideLoading();
      if (res.code === 200) {
        // wx.navigateTo({ 
        //   url: '/pages/ucenter/product/product',
        //   success: function(res) {},
        //   fail: function(res) {},
        //   complete: function(res) {},
        // })
        
        // 返回
        wx.navigateBack({
          delta: 1
        })

      } else {
        util.showErrorToast(res.errmsg);
      }
    });
  },    
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _productId = options.productId;
    if(_productId>0){
      this.setData({
        productId:_productId,
      })   
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.showLoading({
      title: '加载中...',
    });
    // 获得产品信息 
    this.getProductUpdateInfo();  
  },
  onShow: function() {
        
  },
  getProductUpdateInfo: function() {
    let that = this;  
    let _productId = that.data.productId;
    //let _productId = 2022;  
    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,
      categoryName:"车型"
    }   
    _currentCategoryList.push(categoryObj);

    util.request(api.GetProductUpdateInfo,{
      productId:_productId
    }).then(function(res) {
      if (res.code === 200) {
        var _allBrandList = res.dataObject.allBrandList;
        var _allCategoryList = res.dataObject.allCategoryList;
        var _brandId = res.dataObject.brandId;
        var _categoryId = res.dataObject.categoryId;
        var _productName = res.dataObject.productName;
        var _productDetails = res.dataObject.productDetails;
        var _productUnit = res.dataObject.productUnit;
        var _attrTitle = res.dataObject.attrTitle;
        var _attrName = res.dataObject.attrName;
        var _productFiles = res.dataObject.productFiles;
        var _currentPrice = res.dataObject.currentPrice;
        var _productCount = res.dataObject.productCount;
        var _fileServiceLocation = res.dataObject.file_service_location;

        var _brandIndex = 0;
        for (let index = 0; index < _allBrandList.length; index++) {
          const element = _allBrandList[index];
          if(element.id===_brandId){
            _brandIndex = index;
            break;
          }
        }

        for (let idex = 0; idex < _allCategoryList.length; idex++) {
          const element = _allCategoryList[idex];
          if(element.brandId==_brandId){
          _currentCategoryList.push(element);
          }
        }

        var _categoryIndex = 0;
        for (let index = 0; index < _currentCategoryList.length; index++) {
          const element = _currentCategoryList[index];
          if(element.id===_categoryId){
            _categoryIndex = index;
            break;
          }
        }

        var _productFilesAry  =[];
        if(_productFiles){
          _productFilesAry = _productFiles.split(",");
        }
        
        var _fileList = [];
        if(_productFilesAry.length>0){
          for (let index = 0; index < _productFilesAry.length; index++) {
            const element = _productFilesAry[index];
            var fileObj = {
              url:_fileServiceLocation+element,
              name:index+1
            }
            _fileList.push(fileObj);
          }
        } 
        that.setData({
          productId:_productId,
          allBrandList: _allBrandList,
          allCategoryList: _allCategoryList,
          currentCategoryList:_currentCategoryList,
          brandIndex:_brandIndex,
          categoryIndex:_categoryIndex,
          fileServiceLocation:_fileServiceLocation,
          productName:_productName,
          currentPrice:_currentPrice,
          productCount:_productCount,
          productUnit:_productUnit,
          attrName:_attrName,
          content:_productDetails,
          attrTitle:_attrTitle,
          productFiles:_productFilesAry,
          fileList:_fileList
        }); 
      }
      wx.hideLoading();
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})